package com.hp.bon.sgw.wh.mml.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hp.bon.sgw.wh.mml.VCClient;
import com.hp.bon.sgw.wh.mml.common.MMLConstants;
import com.hp.bon.sgw.wh.mml.helper.PropertiesHelper;
import com.hp.bon.sgw.wh.mml.repositories.PropertyRepository;

public class VCMonitorHandler extends Thread {
	
	private static final Logger logger = LoggerFactory.getLogger(VCMonitorHandler.class);
	
	private boolean stop = false;
	
	private static VCMonitorHandler handler = null;
	
	public static void startHandler(){
		if(handler==null){
			handler = new VCMonitorHandler();			
		}
		handler.stop = false;
		handler.start();
	}
	
	public static void stopHandler(){
		handler.stop = true;
	}
	
	public static boolean isRunningHandler(){
		return handler.isAlive();
	}
	
	private VCMonitorHandler(){
		setDaemon(false);
	}
	
	@Override
	public void run() {
		logger.info("VCMonitorHandler is running...");
		while (true) {
			if(stop){
				break;
			}
			logger.info("VC-SGW Connection Status: [" + VCClient.instance().getConnectionStatus() + "]");
			//if VCClient is not connected, try it.
			if(VCClient.instance().getConnectionStatus()==MMLConstants.VC_CONN_FAIL){
				//VCClient.teardownVCClient();
				logger.info("reconnet VC...");
				VCClient.instance().setupVCClient();
			}
			try {
				//check and load property
				PropertiesHelper.loadZBVCProperties();
				//if log server is required, start or stop
				if(PropertyRepository.isLogMsgEnable()){
					MsgLogServerHandler.startHandler();
				} else {
					MsgLogServerHandler.stopHandler();
				}
				
				//sleep 10s
				Thread.sleep(10000);
				
			} catch (Exception e){
				logger.warn("" + e.getMessage());
			}
		}
	}
}
